package com.example.controller;


import com.example.error.BusinessException;
import com.example.model.TestUser;
import com.example.service.TestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zkb
 * @since 2021-06-02
 */
@RestController
@RequestMapping("/user")
public class TestUserController {

    @Autowired
    private TestUserService userService;

    @GetMapping("/getUser")
    public TestUser getUser(@RequestParam Integer id) {
        TestUser user = new TestUser();
        getTestUser1(id,user);


        System.out.println("user" + user);
        return user;
    }

    private void getTestUser1( Integer id,TestUser user) {
        TestUser byId = userService.getById(id);
        if (byId == null) {
            return;
        }
        user.setUsername(byId.getUsername());
     }

    @PostMapping("/saveUser")
    public void saveUser( @RequestBody TestUser user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(bindingResult.getFieldError().getDefaultMessage());
        }
        userService.save(user);
    }

    @DeleteMapping("/upUser")
    public void upUser(@RequestBody TestUser user) {
        userService.updateById(user);
    }


}
